﻿using Microsoft.Data.SqlClient;
using SHRIS.MIS.Common.Util;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;

namespace SHRIS.MIS.Service.RabbitService
{
    public class BulkInserter
    {
        /// <summary>
        /// 批量向表中插入数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="tableName">表名</param>
        /// <param name="list">IList</param>
        public static void AddByBluckCopy<T>(string tableName, ConcurrentQueue<T> list)
        {

            using (SqlBulkCopy bulk = new SqlBulkCopy(GlobalContext.SystemConfig.DBConnectionString))
            {
                bulk.BatchSize = list.Count;
                bulk.DestinationTableName = tableName;

                var table = new DataTable();
                var props = TypeDescriptor.GetProperties(typeof(T)).Cast<PropertyDescriptor>()
                    .Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals("System"))
                    .ToArray();
                foreach (var propertyInfo in props)
                {
                    var columnName = propertyInfo.Attributes[typeof(System.ComponentModel.DataAnnotations.Schema.ColumnAttribute)] as System.ComponentModel.DataAnnotations.Schema.ColumnAttribute;
                    if (columnName != null)
                    {
                        bulk.ColumnMappings.Add(columnName.Name, columnName.Name);
                        table.Columns.Add(columnName.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
                    }
                    else
                    {
                        bulk.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
                        table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType);
                    }
                }

                var values = new object[props.Length];
                foreach (var item in list)
                {
                    for (var i = 0; i < values.Length; i++)
                    {
                        values[i] = props[i].GetValue(item);
                    }

                    table.Rows.Add(values);
                }

                bulk.WriteToServer(table);
            }
        }
    }
}
